<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>运输计划功能测试页面</title>
  <style>
    body {
      font-family: 'Arial', sans-serif;
      padding: 20px;
      max-width: 1200px;
      margin: 0 auto;
      background-color: #f5f5f5;
    }

    .container {
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
    }

    h1,
    h2 {
      color: #333;
      border-bottom: 2px solid #409EFF;
      padding-bottom: 10px;
    }

    .form-group {
      margin-bottom: 15px;
    }

    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
      color: #555;
    }

    input,
    select {
      width: 100%;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
    }

    button {
      background: #409EFF;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-right: 10px;
    }

    button:hover {
      background: #337ecc;
    }

    button:disabled {
      background: #ccc;
      cursor: not-allowed;
    }

    .result {
      margin-top: 20px;
      padding: 15px;
      border: 1px solid #e6e6e6;
      border-radius: 4px;
      background: #fafafa;
    }

    .plan-item {
      background: white;
      padding: 10px;
      margin: 5px 0;
      border-left: 4px solid #409EFF;
      border-radius: 4px;
    }

    .node-tag {
      display: inline-block;
      padding: 2px 8px;
      border-radius: 3px;
      font-size: 12px;
      color: white;
      margin-right: 10px;
    }

    .start {
      background: #67C23A;
    }

    .end {
      background: #F56C6C;
    }

    .transit {
      background: #909399;
    }

    .loading {
      color: #409EFF;
      font-style: italic;
    }

    .error {
      color: #F56C6C;
      background: #FEF0F0;
      padding: 10px;
      border-radius: 4px;
      margin: 10px 0;
    }

    .success {
      color: #67C23A;
      background: #F0F9FF;
      padding: 10px;
      border-radius: 4px;
      margin: 10px 0;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 15px;
    }

    th,
    td {
      padding: 8px 12px;
      text-align: left;
      border-bottom: 1px solid #eee;
    }

    th {
      background: #f8f9fa;
      font-weight: bold;
    }
  </style>
</head>

<body>
  <div class="container">
    <h1>🚛 运输计划功能测试</h1>

    <div class="form-group">
      <label for="billNo">运单编号:</label>
      <input type="text" id="billNo" placeholder="例如: YD202412250001" value="YD202412250001">
    </div>

    <div class="form-group">
      <label for="departureCity">出发城市:</label>
      <input type="text" id="departureCity" placeholder="例如: 长春" value="长春">
    </div>

    <div class="form-group">
      <label for="destinationCity">目的城市:</label>
      <input type="text" id="destinationCity" placeholder="例如: 天津" value="天津">
    </div>

    <button onclick="queryTransportPlan()">查询运输计划</button>
    <button onclick="generateTransportPlan()">生成运输计划</button>
    <button onclick="testCityTransitAPI()">测试城市运输分析API</button>
    <button onclick="clearResults()">清空结果</button>
  </div>

  <div class="container">
    <h2>📋 测试结果</h2>
    <div id="result"></div>
  </div>

  <script>
    const baseURL = 'http://localhost:8080'; // 根据实际情况调整

    function showLoading (message = '处理中...') {
      document.getElementById('result').innerHTML = `<div class="loading">${message}</div>`;
    }

    function showError (message) {
      document.getElementById('result').innerHTML = `<div class="error">❌ 错误: ${message}</div>`;
    }

    function showSuccess (message) {
      document.getElementById('result').innerHTML = `<div class="success">✅ ${message}</div>`;
    }

    function clearResults () {
      document.getElementById('result').innerHTML = '';
    }

    // 查询运输计划
    async function queryTransportPlan () {
      const billNo = document.getElementById('billNo').value;
      if (!billNo) {
        showError('请输入运单编号');
        return;
      }

      showLoading('查询运输计划中...');

      try {
        const response = await fetch(`${baseURL}/system/plan/list?billNo=${encodeURIComponent(billNo)}`);
        const data = await response.json();

        if (data.code === 200) {
          displayTransportPlans(data.rows || [], '查询结果');
        } else {
          showError(data.msg || '查询失败');
        }
      } catch (error) {
        showError('查询异常: ' + error.message);
      }
    }

    // 生成运输计划
    async function generateTransportPlan () {
      const billNo = document.getElementById('billNo').value;
      const departureCity = document.getElementById('departureCity').value;
      const destinationCity = document.getElementById('destinationCity').value;

      if (!billNo || !departureCity || !destinationCity) {
        showError('请填写完整信息');
        return;
      }

      showLoading('生成运输计划中...');

      try {
        // 1. 先调用城市运输分析接口
        const analysisResponse = await fetch(`${baseURL}/pack/locationLog/analysis/cityTransit?departureCity=${encodeURIComponent(departureCity)}&destinationCity=${encodeURIComponent(destinationCity)}`);
        const analysisData = await analysisResponse.json();

        if (analysisData.code !== 200) {
          showError('获取城市运输分析数据失败: ' + (analysisData.msg || '未知错误'));
          return;
        }

        if (!analysisData.data || !analysisData.data.passedCities || analysisData.data.passedCities.length === 0) {
          showError('未获取到有效的运输路径数据');
          return;
        }

        // 2. 将分析数据转换为运输计划格式并保存
        const passedCities = analysisData.data.passedCities;
        const savedPlans = [];

        for (let i = 0; i < passedCities.length; i++) {
          const cityInfo = passedCities[i];

          // 确定节点类型
          let nodeType = '途经点';
          if (i === 0) {
            nodeType = '起点';
          } else if (i === passedCities.length - 1) {
            nodeType = '终点';
          }

          const planData = {
            waybillId: 1, // 测试用
            billNo: billNo,
            locatorId: 1, // 测试用
            locatorCode: 'LOC001', // 测试用
            province: cityInfo.provinceName || '',
            city: cityInfo.cityName || '',
            district: '',
            estimatedDuration: cityInfo.averageStayTime || 0,
            nodeType: nodeType,
            passOrder: cityInfo.passOrder || (i + 1)
          };

          try {
            const saveResponse = await fetch(`${baseURL}/system/plan`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify(planData)
            });
            const saveResult = await saveResponse.json();

            if (saveResult.code === 200) {
              savedPlans.push(planData);
            } else {
              console.error('保存运输计划失败:', saveResult.msg, planData);
            }
          } catch (error) {
            console.error('保存运输计划异常:', error, planData);
          }
        }

        if (savedPlans.length > 0) {
          showSuccess(`成功生成 ${savedPlans.length} 条运输计划记录`);
          // 重新查询显示结果
          setTimeout(() => queryTransportPlan(), 1000);
        } else {
          showError('运输计划保存失败');
        }

      } catch (error) {
        showError('生成运输计划异常: ' + error.message);
      }
    }

    // 测试城市运输分析API
    async function testCityTransitAPI () {
      const departureCity = document.getElementById('departureCity').value;
      const destinationCity = document.getElementById('destinationCity').value;

      if (!departureCity || !destinationCity) {
        showError('请填写出发城市和目的城市');
        return;
      }

      showLoading('调用城市运输分析API中...');

      try {
        const response = await fetch(`${baseURL}/pack/locationLog/analysis/cityTransit?departureCity=${encodeURIComponent(departureCity)}&destinationCity=${encodeURIComponent(destinationCity)}`);
        const data = await response.json();

        if (data.code === 200) {
          displayCityTransitResult(data.data);
        } else {
          showError(data.msg || 'API调用失败');
        }
      } catch (error) {
        showError('API调用异常: ' + error.message);
      }
    }

    // 显示运输计划列表
    function displayTransportPlans (plans, title) {
      if (!plans || plans.length === 0) {
        document.getElementById('result').innerHTML = `
                    <h3>${title}</h3>
                    <p>暂无运输计划数据</p>
                `;
        return;
      }

      let html = `<h3>${title} (共${plans.length}条)</h3>`;

      html += `
                <table>
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>经过顺序</th>
                            <th>城市</th>
                            <th>省份</th>
                            <th>节点类型</th>
                            <th>预计耗时(小时)</th>
                            <th>创建时间</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

      plans.forEach((plan, index) => {
        const nodeClass = plan.nodeType === '起点' ? 'start' : plan.nodeType === '终点' ? 'end' : 'transit';
        html += `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${plan.passOrder || '-'}</td>
                        <td>${plan.city || '-'}</td>
                        <td>${plan.province || '-'}</td>
                        <td><span class="node-tag ${nodeClass}">${plan.nodeType || '-'}</span></td>
                        <td>${plan.estimatedDuration ? plan.estimatedDuration.toFixed(1) : '-'}</td>
                        <td>${plan.createTime ? new Date(plan.createTime).toLocaleString() : '-'}</td>
                    </tr>
                `;
      });

      html += `
                    </tbody>
                </table>
            `;

      document.getElementById('result').innerHTML = html;
    }

    // 显示城市运输分析结果
    function displayCityTransitResult (data) {
      let html = `
                <h3>🗺️ 城市运输分析结果</h3>
                <div class="plan-item">
                    <strong>出发城市:</strong> ${data.departureCity || '-'}<br>
                    <strong>目的城市:</strong> ${data.destinationCity || '-'}<br>
                    <strong>运单数量:</strong> ${data.wayBillCount || 0}<br>
                    <strong>总运输时间:</strong> ${data.totalTransitTime ? data.totalTransitTime.toFixed(1) + ' 小时' : '-'}
                </div>
            `;

      if (data.passedCities && data.passedCities.length > 0) {
        html += `<h4>📍 途经城市 (共${data.passedCities.length}个)</h4>`;

        data.passedCities.forEach((city, index) => {
          const nodeClass = index === 0 ? 'start' : index === data.passedCities.length - 1 ? 'end' : 'transit';
          const nodeTypeName = index === 0 ? '起点' : index === data.passedCities.length - 1 ? '终点' : '途经点';

          html += `
                        <div class="plan-item">
                            <span class="node-tag ${nodeClass}">${nodeTypeName}</span>
                            <strong>第${city.passOrder || (index + 1)}站: ${city.cityName || '-'}</strong>
                            ${city.provinceName ? `(${city.provinceName})` : ''}
                            <br>
                            到下一城市平均用时: ${city.averageStayTime ? city.averageStayTime.toFixed(1) + ' 小时' : '-'}
                        </div>
                    `;
        });
      }

      document.getElementById('result').innerHTML = html;
    }

    // 页面加载完成后的初始化
    document.addEventListener('DOMContentLoaded', function () {
      console.log('运输计划测试页面已加载');
    });
  </script>
</body>

</html>